package com.bojx.report.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
	public static void main(String[] args) throws InterruptedException {
		int port;
		ServerSocket serverSocket;
		try{
			port=Integer.parseInt(args[0]);
		}catch(Exception e){
			port=8080;
		}
		
		try {
			serverSocket=new ServerSocket(port);
			System.out.println("服务端正在监听端口："+serverSocket.getLocalPort());
			while(true){
				System.out.println("----");
				final Socket socket=serverSocket.accept();
				System.out.println("建立了一个TCP连接，该客户的地址为："+socket.getInetAddress()+":"
						+socket.getPort());
				service(socket);//响应客户请求
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
		
		
	}

	private static void service(Socket socket) throws IOException, InterruptedException {
		InputStream inputSocket=socket.getInputStream();
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int size=inputSocket.available();
		byte[] buffer=new byte[size];
		inputSocket.read(buffer);
		String request=new String(buffer);
		System.out.println(request);//打印http请求数据
		/*解析http请求*/
		//获取第一行
		String firstLineOfRequest=request.substring(0,request.indexOf("\r\n"));
		/*解析第一行*/
		String[] parts=firstLineOfRequest.split(" ");
		String uri=parts[0];//获取响应的URI
		
		//获取正文类型
		String contentType;
		if(uri.indexOf(".html")!=-1 ||uri.indexOf(".htm")!=-1 ){
			contentType="text/html";
		}else if(uri.indexOf(".jpg")!=-1 ||uri.indexOf(".jpeg")!=-1){
			contentType="image/jpeg";
		}else if(uri.indexOf(".gif")!=-1 ){
			contentType="image/gif";
		}else{
			contentType="application/octet-stream";//字节流类型
		}
		
		
		//发送http响应结果
		 
		String responseFirstLine="HTTP/1.1 200 OK\r\n";
		OutputStream os=socket.getOutputStream();
		os.write(responseFirstLine.getBytes());
		Thread.sleep(200); 
		os.close();
	}
}
